package com.bw.service;

import com.bw.bean.City;
import com.bw.bean.Houses_trading;
import com.bw.bean.Region;
import com.bw.bean.Trading;
import com.bw.dao.RegionDao;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RegionServiceImpl implements RegionService {

    @Resource
    private RegionDao regionDao;

    @Override
    public List<Region> list(Region region) {
        return regionDao.list(region);
    }

    @Override
    public void save(Region region,String tids) {
        //给主表插入数据，主要mapper里边配置返回主键id
        int rid = region.getRid();
        if(rid ==0){
            regionDao.insert(region);
        }else{
            regionDao.update(region);
            //修改时，要根据rid删除中间表就的关联数据,后边再重新增加
            regionDao.deleteByRid(rid);
        }
        //如果传入tids（复选框）不为空，那么给中间表批量插入数据
        if(StringUtil.isNotEmpty(tids)){
            List<Houses_trading> list = new ArrayList<>();
            String[] split = tids.split(",");
            for (int i = 0; i < split.length; i++) {
                Houses_trading houses_trading = new Houses_trading();
                houses_trading.setRid(region.getRid());
                houses_trading.setTid(Integer.parseInt(split[i]));
                list.add(houses_trading);
            }
            regionDao.insertbth(list);
        }

    }

    @Override
    public Region getById(int rid) {
        return regionDao.getById(rid);
    }


    @Override
    public void insertbth(List<Houses_trading> list) {
        regionDao.insertbth(list);
    }

    @Override
    public void deleteByRid(int rid) {
        regionDao.deleteByRid(rid);
    }

    @Override
    public List<City> getByPid(int pid) {
        return regionDao.getByPid(pid);
    }

    @Override
    public List<Trading> getTradings(int xid) {
        return regionDao.getTradings(xid);
    }
}
